package com.zzzzzz.oms.legs;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zzzzzz.core.datagrid.BaseData;
import com.zzzzzz.oms.orderHead.OrderHead;
import com.zzzzzz.oms.orderHead.OrderHeadDao;
import com.zzzzzz.oms.shipment.Shipment;
import com.zzzzzz.oms.shipment.ShipmentDao;
import com.zzzzzz.oms.tempShipment.TempShipment;
import com.zzzzzz.oms.tempShipment.TempShipmentDao;
import com.zzzzzz.plugins.shiro.I;
import com.zzzzzz.utils.BeanValidators;
import com.zzzzzz.utils.DateTimeUtils;

@Service
public class LegsService {
	@Resource
	public LegsDao legsDao;
	@Resource
	public OrderHeadDao orderHeadDao;
	@Resource
	public Validator validator;
	@Resource 
	public TempShipmentDao tempShipmentDao;
	@Resource 
	public ShipmentDao shipmentDao;
	@Transactional
	public int save(Legs legs, I i) {
		legs.setUpdDt(new Date());
		legs.setUpdBy(i.getId());
		if (legs.getId() == null) {
			legs.setAddDt(new Date());
			legs.setAddBy(i.getId());
			legsDao.add(legs);
		} else {
			legsDao.updById(legs);
		}

		return 1;
	}
	
	public int findByShipmentId(List<Long> shipmentIds,String status,I i){
		List<Legs> list=legsDao.findByShipmentId(shipmentIds);
		List<Long> list1=new ArrayList<Long>();
		if(list.size()>0){
			for(Legs legs:list){
				list1.add(legs.getOrderId());
			}
			orderHeadDao.updStByIds(list1, status,i);
		}
		return 1;
	}
	
	@Transactional
	public BaseData batchAdd(List<Legs> list, I i) {
		logger.info("legs batchAdd validate start:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		//start validate
		int errTt = 0;
		StringBuilder errMsg = new StringBuilder();
		for (Legs legs : list) {
			try {
				BeanValidators.validateWithException(validator, legs);
			} catch (ConstraintViolationException e) {
				List<String> msgList = BeanValidators.extractPropertyAndMessageAsList(e, ": ");
				for (String msg : msgList) {
					errTt++;
					errMsg.append("<br/>").append(msg);
				}
			} catch (Exception e) {
				logger.warn("", e);
				errTt++;
				errMsg.append("<br/>验证失败：").append(e.getMessage());
			}
		}
		if(errTt > 0){
			errMsg.insert(0, "共有"+errTt+"笔记录验证失败：");
			return new BaseData("101", errMsg.toString());
		}
		logger.info("legs batchAdd validate end:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		logger.info("legs batchAdd save start:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		//state save
		int susTt = 0;
		for (Legs legs : list) {
			save(legs, i);
			susTt++;
		}
		logger.info("legs batchAdd save end:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		return new BaseData("0", "共有"+susTt+"笔记录导入成功。");
	}
	//生成legs	
		public Legs add(OrderHead orderHead,I i){
			Legs legs=new Legs();
			legs.setOrderId(orderHead.getId());
			legs.setOrderCd(orderHead.getCd());
			legs.setLegs_no(orderHead.getCd()+"_1");
			legs.setSt("shipment");
			legs.setStatus(orderHead.getStatus());
			legs.setPlatformId(i.getPlatformId());
			legs.setAddDt(new Date());
			legs.setAddBy(i.getId());
			legs.setVocationType(orderHead.getVocation());
			legs.setClientId(orderHead.getClientId());
			if(tempShipmentDao.findIdByCd("未配载", orderHead.getVocation(),i)==null){
				tempShipmentDao.add1(orderHead.getVocation(), i);
			}
			legs.setTempshipmentId(tempShipmentDao.findIdByCd("未配载", orderHead.getVocation(),i).getId());
			legs.setShipment_method(orderHead.getShipment_method());
			legs.setFormId(orderHead.getFreceiverId());
			legs.setToId(orderHead.getTreceiverId());
			legs.setFtranslocationId(orderHead.getFtranslocationId());
			legs.setTtranslocationId(orderHead.getTtranslocationId());
			legs.setFormName(orderHead.getFreceiverName());
			legs.setFormlikeName(orderHead.getFreceiverLikename());
			legs.setFormPhone(orderHead.getFreceiverPhone());
			legs.setFormAddr(orderHead.getFreceiverAddress());
			legs.setToName(orderHead.getTreceiverName());
			legs.setTolikeName(orderHead.getTreceiverLikename());
			legs.setToPhone(orderHead.getTreceiverPhone());
			legs.setToAddr(orderHead.getTreceiverAddress());
			legs.setQuantity(orderHead.getQuantity());
			legs.setWeight(orderHead.getWeight());
			legs.setVolume(orderHead.getVolume());
			legs.setPalletsum(orderHead.getPalletsum());
			legs.setExpense(orderHead.getExpense());
			legs.setOrdertime(orderHead.getOrderDt());
			legs.setBilltime(orderHead.getBillingDt());
			legs.setPlanltime(orderHead.getPlanlDt());
			legs.setPlanatime(orderHead.getPlanaDt());
			return legs;
		}
		
		//调度订单里面取消分段订单
		public void updByIds(List<Legs> list, List<Long> ids,String vocationType,Long shipmentId,I i){
			TempShipment temp=tempShipmentDao.findIdByCd("未配载", vocationType, i);
			legsDao.updByIds(ids, temp.getId(), i);
			change(list,shipmentId, temp, i);
		}
		
		//调度单里面增加分段订单
		public void updByIds1(List<Legs> list,List<Long> ids,Long shipmentId,Long constractorId,String shipment_method,String vocationType,I i){
			TempShipment temp=tempShipmentDao.findIdByCd("未配载", vocationType, i);
			legsDao.updByIds1(ids, shipmentId, constractorId, shipment_method, i);
			change1(list, shipmentId, temp, i);
		}
		
		//更新temp和shipment
		public void change(List<Legs> list,Long shipmentId,TempShipment temp,I i){
			Double quantity=0.0;
			Double weight=0.0;
			Double volume=0.0;
			Integer count=0;
			Integer count1=0;
			for(Legs legs:list){
				quantity+=legs.getQuantity();
				weight+=legs.getWeight();
				volume+=legs.getVolume();
			}
			count=legsDao.findCount(temp.getId());
			count1=legsDao.findCount1(shipmentId);
			tempShipmentDao.updStById(temp.getId(),temp.getQuantity()+quantity, temp.getPoints()+list.size(), temp.getWeight()+weight, temp.getVolume()+volume, count, i);
			Shipment shipment= shipmentDao.findById(shipmentId);
			shipmentDao.upds(shipmentId, shipment.getQuantity()-quantity, shipment.getWeight()-weight, shipment.getVolume()-volume, count1, i);
		}
		
		//更新temp和shipment
		public void change1(List<Legs> list,Long shipmentId,TempShipment temp,I i){
			Double quantity=0.0;
			Double weight=0.0;
			Double volume=0.0;
			Integer count=0;
			Integer count1=0;
			for(Legs legs:list){
				quantity+=legs.getQuantity();
				weight+=legs.getWeight();
				volume+=legs.getVolume();
			}
			count=legsDao.findCount(temp.getId());
			count1=legsDao.findCount1(shipmentId);
			tempShipmentDao.updStById(temp.getId(),temp.getQuantity()-quantity, temp.getPoints()-list.size(), temp.getWeight()-weight, temp.getVolume()-volume, count, i);
			Shipment shipment= shipmentDao.findById(shipmentId);
			shipmentDao.upds(shipmentId, shipment.getQuantity()+quantity, shipment.getWeight()+weight, shipment.getVolume()+volume, count1, i);
		}
	private static final Logger logger = LoggerFactory.getLogger(Legs.class);
}
